package com.aydx.minirpc.core.common;

/**
 * Created by eloancn on 2017/3/13.
 * byte操作工具类
 */
public class ByteUtils {
    /**
     * 截取byte数组
     * @param bytes 源数组
     * @param start 开始索引
     * @param length 长度
     * @return 截取的数组
     */
    public static byte[] split(byte[] bytes,int start,int length){
        byte[] target=new byte[length];
        System.arraycopy(bytes,start,target,0,length);
        return target;
    }

    /**
     * byte数组转bit位字符串
     * @param bs
     * @return
     */
    public static String byteArrayToBit(byte[] bs){
        if(bs==null||bs.length==0){
            return "";
        }
        String result="";
        for(int i=0;i<bs.length;i++){
            result=result+byteToBit(bs[i]);
        }
        return result;
    }

    /**
     * byte转bit为字符串
     * @param b
     * @return
     */
    public static String byteToBit(byte b) {
        return ""
                + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
                + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
                + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
                + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
    }

    public static byte[] concat(byte[] a, byte[] b) {
        byte[] c= new byte[a.length+b.length];
        System.arraycopy(a, 0, c, 0, a.length);
        System.arraycopy(b, 0, c, a.length, b.length);
        return c;
    }

    public static void main(String[] args) {
        byte[] a=new byte[]{1,2,3};
        byte[] b=new byte[]{4,5,6};
        byte[] c=concat(a,b);
        System.out.println(c.length);
    }
}
